﻿using UnityEngine;
using UnityEditor;
using System.Collections;
using System.IO;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;

public class ParseComponentsTools :Editor
{
    //脚本关联
    static Dictionary<string, List<string>> nguics = new Dictionary<string, List<string>>();
    /// <summary>
    /// 预制路径
    /// </summary>
    static List<string> prefabPath = new List<string>();
    static string serializepath = Application.dataPath + "/CsDependency.txt";
    [MenuItem("Tools/ClearScriptsComponents",false,100)]
    public static void ClearScripts()
    {
        Debug.Log("Clear Scripts");
        nguics.Clear();
        //路径
        string fullPath = "Assets/Resources/Prefabs" + "/";
        prefabPath.Clear();
        //获取指定路径下面的所有资源文件
        if (Directory.Exists(fullPath))
        {
            DirectoryInfo direction = new DirectoryInfo(fullPath);
            FileInfo[] files = direction.GetFiles("*.prefab", SearchOption.AllDirectories);

            Debug.Log(files.Length);

            for (int i = 0; i < files.Length; i++)
            {
                if (files[i].Name.EndsWith(".meta"))
                {
                    continue;
                }
                else
                {
                    //Debug.Log("Name:" + files[i].Name+"fullPath:"+files[i].FullName);
                    Debug.Log("<color=red>---------------------------------完整预制分割线----------------------------------------</color>");
                    string path = files[i].FullName.Replace('\\','/');
                    path = "Assets"+path.Replace(Application.dataPath, "");
                    if (prefabPath.Contains(path))
                        continue;
                    else
                    {
                        prefabPath.Add(path);
                    }
                    GameObject o = AssetDatabase.LoadAssetAtPath(path,typeof(GameObject))as GameObject;
                    Debug.Log(o.name);
                    if (null == o)
                    {
                        UnityEngine.Debug.LogError(files[i] + " is null");
                        continue;
                    }
                    else
                    {
                        Component[] comps = o.GetComponentsInChildren<Component>(true);
                        foreach (var comp in comps)
                        {
                            if (null == comp)
                            {
                                Debug.LogError(comp + "is null");
                                continue;
                            }
                            string child = NGUITools.GetHierarchy(comp.gameObject);
                            //Debug.Log("origin:"+child);
                            int idx = child.IndexOf('\\');
                            if (idx != -1)
                            {
                                child = child.Substring(idx + 1);
                            }
                            child = child.Replace('\\', '/');
                            //Debug.Log("after:"+child);


                            string typeName = comp.GetType().ToString();
                            //Debug.Log(typeName);
                            if (typeName.StartsWith("UnityEngine"))//unity transform boxcolider...
                            {
                                //Object.DestroyImmediate(comp, true);
                                Debug.Log(comp.name);
                            }
                            else//获得cs脚本
                            {
                                Debug.Log("<color=yellow>Scripts: "+ typeName + "</color>");
                                if (!nguics.ContainsKey(comp.name))
                                {
                                    nguics.Add(comp.name, new List<string>());
                                  
                                }
                                if (nguics[comp.name].Contains(typeName))
                                    continue;
                                else
                                    nguics[comp.name].Add(typeName);
                                //Object.DestroyImmediate(comp, true);
                            }
                        }
                    }
                }
                //Debug.Log("FullName:" + files[i].FullName);
                AssetDatabase.Refresh();
            }
            Serialize(nguics, serializepath);
        }

        //foreach (var pair in nguics)
        //{
        //    Debug.Log(pair.Key);
        //    foreach (var item in pair.Value)
        //    {
        //        Debug.Log(item);
        //    }
        //}
    }
    [MenuItem("Tools/ReadDependency", false, 100)]
    public static void ReadDependency()
    {
        nguics.Clear();
        nguics = DeSerialize<Dictionary<string, List<string>>>(serializepath);
        foreach (var pair in nguics)
        {
            Debug.Log("<color=red>" + pair.Key + "</color>");
            for (int i = 0; i < pair.Value.Count; i++)
            {
                Debug.Log(pair.Value[i]);
            }
        }
        AssetDatabase.Refresh();
    }

    [MenuItem("Tools/ReverseScriptCS", false, 100)]
    public static void ReverseScriptsCS()  //递归绑定脚本
    {
        nguics.Clear();
        nguics = DeSerialize<Dictionary<string, List<string>>>(serializepath);
        string fullPath = "Assets/Resources/Prefabs" + "/";
        foreach (var pair in nguics)
        {
            Debug.Log(fullPath + pair.Key);
            GameObject root = AssetDatabase.LoadAssetAtPath(fullPath + pair.Key+".prefab", typeof(GameObject)) as GameObject;//本地资源路径
            if (root == null)
            {
                Debug.LogError("can't find:"+ fullPath + pair.Key + ".prefab");
                continue;
            }
            if (root.transform.childCount > 0)
            {
                BingScripts(root.transform, nguics[pair.Key]);
                for (int i = 0; i < root.transform.childCount; i++)
                {
                    Debug.Log(root.transform.GetChild(i).name);
                    BingScripts(root.transform.GetChild(i), nguics[pair.Key]);
                }
            }
            else
            {
                BingScripts(root.transform, nguics[pair.Key]);
            }
        }
    }

    /// <summary>
    /// 绑定脚本组件
    /// </summary>
    /// <param name="tran"></param>
    /// <param name="scriptsName"></param>
    public static void BingScripts(Transform tran,List<string> scriptsName)
    {
        Debug.Log(scriptsName.Count);
        foreach (var script in scriptsName)
        {
            Debug.Log(string.Format("<color=yellow>开始绑定{0}</color>", script));
            //tran.gameObject.AddComponent(System.Type.GetType(script));
        }
    }



    /// <summary>
    /// 序列化信息
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="t"></param>
    /// <param name="path"></param>
    public static void Serialize<T>(T t, string path)
    {
        Debug.Log(path);
        if (File.Exists(path))
        {
            File.Delete(path);
        }
        try
        {
            BinaryFormatter formatter = new BinaryFormatter();
            Stream stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
            formatter.Serialize(stream, t);
            stream.Flush();
            stream.Close();
        }
        catch (System.Exception e)
        {
            Debug.Log(e.Message);
        }
    }

    /// <summary>
    /// 反序列化
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="path"></param>
    /// <returns></returns>
    public static  T DeSerialize<T>(string path)
    {
        if (!File.Exists(path))
            return default(T);
        try
        {
            BinaryFormatter formatter = new BinaryFormatter();
            Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
            T t = (T)formatter.Deserialize(stream);
            stream.Flush();
            stream.Close();
            return t;
        }
        catch (System.Exception e)
        {
            Debug.Log(e.Message);
        }
        return default(T);
    }

    //Unity 一键修改项目中所有模型动画压缩模式
    [MenuItem("Tools/SearchFile")]
    public static  void SearchFile()
    {
        var assets = AssetDatabase.FindAssets("t:GameObject");
        AssetDatabase.StartAssetEditing();
        foreach (var guid in assets)
        {
            var assetPath = AssetDatabase.GUIDToAssetPath(guid);
            var modelImporter = AssetImporter.GetAtPath(assetPath) as ModelImporter;
            if (modelImporter == null)
                continue;
            if (modelImporter.importAnimation && modelImporter.animationCompression != ModelImporterAnimationCompression.Optimal)
            {
                modelImporter.animationCompression = ModelImporterAnimationCompression.Optimal;
                modelImporter.SaveAndReimport();
            }
        }
        AssetDatabase.StopAssetEditing();
        AssetDatabase.Refresh();
    }
}
